<template>
  <el-form
    :model="orderForm"
    label-width="100px"
    :rules="orderFormRules"
    ref="orderForm"
  >
    <el-card class="box-card" v-show="isQr">
      <div class="equipmentBox">
        <div class="equipment-title">报修设备信息</div>
        <div class="equipment-item">设备名称：{{ equipment.ename }}</div>
        <div class="equipment-item">设备类型：{{ equipment.eclass }}</div>
        <div class="equipment-item">
          设备型号：{{
            equipment.eworker == null ? '未知型号' : equipment.eworker
          }}
        </div>
        <div class="equipment-item">
          设备使用单位：{{
            equipment.usingUnit == null ? '未指定使用单位' : equipment.usingUnit
          }}
        </div>
      </div>
    </el-card>

    <!-- 联系人名称 -->
    <el-form-item label="联系人名称" prop="contacts">
      <el-input v-model="orderForm.contacts"></el-input>
    </el-form-item>
    <!-- 选择报修类型 -->
    <el-form-item label="报错类型" prop="faultClass" v-show="!isQr">
      <el-select v-model="orderForm.faultClass" placeholder="请选择报错类型">
        <el-option
          v-for="(item, index) in faultList"
          :key="index"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
    </el-form-item>
    <!-- 详细地址 -->
    <el-form-item label="详细地址" prop="address" v-show="!isQr">
      <el-input v-model="orderForm.address" :disabled="isQr"></el-input>
    </el-form-item>
    <!-- 手机号 -->
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="orderForm.phone" size="medium"></el-input>
    </el-form-item>
    <!-- 错误描述 label-width='0px' 可以使之无左边描述 -->
    <el-form-item label-width="0px" prop="faultDetails">
      <el-input
        type="textarea"
        :rows="10"
        v-model="orderForm.faultDetails"
        placeholder="错误描述"
      ></el-input>
    </el-form-item>
    <!-- 上传图片 -->
    <el-form-item class="upload_image">
      <el-upload
        :action="uploadUrl"
        accept="image/jpeg,image/png"
        list-type="picture"
        :limit="3"
        :before-upload="beforeAvatarUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        ><el-button size="small" type="primary">添加图片</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传 3 张 jpg/png 文件 且文件不能超过 2MB
        </div>
      </el-upload>
    </el-form-item>
    <el-dialog :visible.sync="dialogVisible" style="padding: 10px 0px">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-button round type="primary" class="submit" @click="submitForm()"
      >提交</el-button
    >
  </el-form>
</template>

<script>
export default {
  created() {
    this.getFaultClass()

    const equipment = this.$route.params.equipment

    // 如果没有参数则跳过
    if (equipment == null || !equipment || equipment === undefined) {
    } else {
      this.equipment = equipment
      this.isQr = true
    }
  },
  data() {
    return {
      isQr: false,
      equipment: {},
      tempName: '',
      dialogImageUrl: '',
      dialogVisible: false,
      orderFormRules: {
        contacts: [
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        phone: [
          {
            validator: this.checkPhone,
            trigger: 'blur'
          }
        ]
      },
      uploadUrl: `${this.$http.defaults.baseURL}student/upload`,
      orderForm: {
        phone: '',
        address: '',
        contacts: '',
        faultClass: '',
        faultDetails: '',
        file_list: []
      },
      faultList: []
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      return isLt2M
    },
    handleError() {
      console.log('上传失败')
      return this.$message.error('上传失败')
    },
    handleSuccess(response, file, fileList) {
      console.log(response)
      this.orderForm.file_list.push(response.data)
      console.log(this.orderForm.file_list)
      console.log('上传成功')
    },
    handleRemove(file, fileList) {
      console.log(fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    checkPhone(rule, value, callback) {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    },
    getFaultClass() {
      this.$http
        .get('utils/fault-class')
        .then(res => {
          // 因为数组不是响应式更新，所以需要手动
          this.faultList = res.data.data
        })
        .catch(() => {
          return this.$message.error('取得列表失败！')
        })
    },
    submitForm() {
      // 手动上传图片
      this.$refs.orderForm.validate(validate => {
        if (!validate) {
          return this.$message.error('请把信息填写完整！')
        }
        let str = ''
        for (const iterator of this.orderForm.file_list) {
          str += iterator + ','
        }

        if (!this.isQr) {
          this.$http
            .post('student/order', {
              studentPhone: this.orderForm.phone,
              address: this.orderForm.address,
              contacts: this.orderForm.contacts,
              faultClass: this.orderForm.faultClass,
              faultDetails: this.orderForm.faultDetails,
              images: str
            })
            .then(res => {
              this.$message.success({ message: '提交订单成功', duration: 500 })
              this.$router.push('myOrder')
            })
            .catch(error => {
              console.log(error)
              return this.$message.error('提交订单失败')
            })
        } else {
          // this.equipment.id
          this.$http
            .post('student/order-qt', {
              id: this.equipment.id,
              studentPhone: this.orderForm.phone,
              contacts: this.orderForm.contacts,
              faultDetails: this.orderForm.faultDetails,
              images: str
            })
            .then(res => {
              this.$message.success({ message: '报修设备成功', duration: 500 })
              this.$router.push('myOrder')
            })
            .catch(error => {
              console.log(error)
              return this.$message.error('报修设备失败')
            })
        }
      })
    }
  }
}
</script>

<style lang='less' scoped>
.box-card {
  margin-bottom: 10px;
  .equipmentBox {
    .equipment-title {
      font-weight: bold;
    }
    .equipment-item {
      margin-top: 2px;
      color: rgb(117, 117, 117);
    }
  }
}

.upload_image /deep/ .el-form-item__content {
  margin-left: 0px !important;
  .el-button {
    position: relative;
    left: 100%;
    transform: translate(50%, 0);
  }
  .el-upload__tip {
    text-align: center;
  }
}

.submit {
  position: fixed;
  left: 75%;
  bottom: 10%;
  z-index: 10;
}
</style>
